﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using NLog;

namespace ConsoleService
{
    public partial class ServerService : ServiceBase
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();

        private System.Threading.Thread _monitor;

        public ServerService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            StartService(args);
        }

        public void StartService(string[] args)
        {
            logger.Info("Starting the program");
            ServerMonitor.CanRun = true;
            this._monitor = new System.Threading.Thread(new System.Threading.ThreadStart(ServerMonitor.Run));
            this._monitor.Start();
            logger.Info("Started Successfully!");
        }

        protected override void OnStop()
        {
            StopService();
        }

        public void StopService()
        {
            logger.Info("Program is stopping");
            ServerMonitor.CanRun = false;
            var start = DateTime.Now;
            while (this._monitor.IsAlive && DateTime.Now.Subtract(start).TotalSeconds < 30)
            {
                System.Threading.Thread.Sleep(500);
            }
            if (this._monitor.IsAlive)
            {
                logger.Info("Aborting the Monitor Thread");
                this._monitor.Abort();
            }
            else
            {
                logger.Info("Monitor Thread successfully stopped!");
            }
            logger.Info("Stopped Successfully");
        }
    }
}
